#include <stdio.h>
#include <err.h>
#include <assert.h>

int xatoi(char *str)
{
    assert(str != NULL);
    int n = 0, ch, flag = 1, overflowFlag = 0;

    while ((ch = *str) == ' ')
	++str;

    if ('-' == ch) {
	flag = -1;
	ch = *(++str);
    } else if ('+' == ch) {
	ch = *(++str);
    }

    while (ch != '\0') {
	assert(ch >= '0' && ch <= '9');
	n = n*10 + ch - '0';

	if (!overflowFlag && n < 0) {
	    overflowFlag = 1;
	    warnx("integer overflow!");
	}
	
	ch = *(++str);
    }

    return flag*n;
}

int main(int argc, char *argv[])
{
    int n;
    n = xatoi(argv[1]);

    printf("str = \"%s\" -> int = %d\n", argv[1], n);
    return 0;
}
